package com.game.serivce;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import net.SocketEnum;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;

import com.component.code.TishiManager;
import com.data.WDataConversion;
import com.data.cache.DeskPlayerServiceCache;
import com.data.third.DataService;
import com.dictionary.DictionaryTabel;
import com.game.android.AndroidManage;
import com.game.android.AndroidService;
import com.game.model.ConfigRoomService;
/**
 * 游戏房间服务
 * @author wuxiaojian
 *
 */
public class GameRoomService {
	private Logger logger = Logger.getLogger(GameRoomService.class.getName());
	public ConfigRoomService configRoomService;
	public RoomDeskService[] roomDeskServices;
	public AndroidManage androidManage;
	public GuangboService guangboService;
	/**等待加入桌子的玩家队列**/
	public ArrayList<DeskPlayerService> waitJoinPlayers = new ArrayList<DeskPlayerService>();
	/**桌子还有空位队列**/
	public ArrayList<RoomDeskService> haveWaitPlayerDeskServices = new ArrayList<RoomDeskService>();
	public GameRoomService(ConfigRoomService configRoomService){
		init(configRoomService);
	}
	public RoomDeskService[] getRoomDeskServices() {
		return roomDeskServices;
	}

	public void setRoomDeskServices(RoomDeskService[] roomDeskServices) {
		this.roomDeskServices = roomDeskServices;
	}
	
	
	public ConfigRoomService getConfigRoomService() {
		return configRoomService;
	}

	public void setConfigRoomService(ConfigRoomService configRoomService) {
		this.configRoomService = configRoomService;
	}
	//初始化 桌子，广播,机器人服务
	public void init(ConfigRoomService configRoomService){
		this.configRoomService = configRoomService;
		int deskCount = configRoomService.oneRoomhaveDeskCount;
		//桌子服务初始化
		roomDeskServices = new RoomDeskService[deskCount];
		for (int i = 0; i < deskCount; i++) {
			roomDeskServices[i] = new RoomDeskService(this,configRoomService,i);
		}
		//机器人管理器启动
		//androidManage = new AndroidManage(this);
		//广播服务初始化
		//guangboService = new GuangboService(this);
		//
		setTimerTask();
	}
	
	public void joinRoom(DeskPlayerService dps) {
		System.out.println(1111);
		if (dps.playerService.deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_People) {
			//真人进入
			if (isCanJoinRoom(dps)) {
				if (!waitJoinPlayers.contains(dps)) {
					DataService.intoRoom(dps.playerService.deskPlayer.getPlayerId(), dps.playerService.deskPlayer.getGameNum(), dps.playerService.deskPlayer.getRoomNum());
					waitJoinPlayers.add(dps);
				}
			}
		} else {
			//机器人进入
			if (isCanJoinRoom(dps)) {
				if (!waitJoinPlayers.contains(dps))
					waitJoinPlayers.add(dps);
			} else {
				dps.playerService.changePropNum(2, WDataConversion.randLong(androidManage.gameRoomService.configRoomService.androidHaveMoney[0],
						androidManage.gameRoomService.configRoomService.androidHaveMoney[1]));
				AndroidService androidService = (AndroidService) dps;
				if (!androidManage.androidServices_Available.contains(androidService)) {
					androidManage.androidServices_Available.add(androidService);
				}
			}
		}
	}
	
	public void reJoinRoom(DeskPlayerService dps) {
		if (dps.playerService.deskPlayer.getDeskNum() == -1 || dps.playerService.deskPlayer.getSeatNum() == -1) {
			joinRoom(dps);
		} else {
			RoomDeskService roomDeskService = dps.getRoomDeskService();
			
			if (roomDeskService == null)
				roomDeskService = roomDeskServices[dps.playerService.deskPlayer.getDeskNum()];
			
			if (roomDeskService == null) {
				joinRoom(dps);
			} else {
				roomDeskService.reIntoDesk(dps);
			}
		}
	}
	public void leaveRoom(DeskPlayerService dps) {
		DataService.leaveRoom(dps.playerService.deskPlayer.getPlayerId(), dps.playerService.deskPlayer.getGameNum(), dps.playerService.deskPlayer.getRoomNum());
		DeskPlayerServiceCache.SessionMap.remove(dps.playerService.deskPlayer.getPlayerId());
		dps = null;
	}
	public String getOnlineCount() {
		int realCount = 0;
		int allCount = 0;
		
		for(int i = 0; i < roomDeskServices.length; i++)
		{
			if (roomDeskServices != null)
			{
				realCount = realCount + roomDeskServices[i].getRealPlayersCount();
				allCount = allCount + roomDeskServices[i].getPlayersCount();
			}
		}
		
		return realCount + "|" + allCount;
	}
	
	private boolean isCanJoinRoom(DeskPlayerService dps) {
		//房间是否开启
		if (configRoomService.isOpen == 0) {
			dps.playerService.sendMessage(SocketEnum.infoI, TishiManager.Tishi_T_Room_Close);
			return false;
		}
		//房间入场限制
		if (dps.playerService.getPropNum(2) < configRoomService.roomLimitMoneyMin) {
			dps.playerService.sendMessage(SocketEnum.infoI, TishiManager.Tishi_T_MoneyTooLow);
			return false;
		}
			
		if (dps.playerService.getPropNum(2) > configRoomService.roomLimitMoneyMax) {
			dps.playerService.sendMessage(SocketEnum.infoI, TishiManager.Tishi_T_MoneyTooHigh);
			return false;
		}
		
		return true;
	}
	
	private ScheduledExecutorService scheduExec = Executors.newSingleThreadScheduledExecutor();
	private void setTimerTask() {
		Runnable task = new Runnable() {
			public void run() {
				try {
					if (waitJoinPlayers.size() > 0) {
						DeskPlayerService dps = waitJoinPlayers.get(0);
						System.out.println("waitJoinPlayers"+waitJoinPlayers.size());
						try {
							waitJoinPlayers.remove(0);
							//查找可以加入的桌子
							RoomDeskService roomDeskService = getHaveWaitPlayerDeskService(dps);
							//加载进度条
							if (roomDeskService != null) {
								//加入桌子成功
								if (roomDeskService.intoDesk(dps)) {
									//桌子还有空位，加入等待玩家队列
									if (roomDeskService.getPlayersCount() < configRoomService.oneDeskhavePlayerCount) {
										if (!haveWaitPlayerDeskServices.contains(roomDeskService)) {
											haveWaitPlayerDeskServices.add(roomDeskService);
										}
									}
									//桌子满人，从等待玩家队列移除
									if (roomDeskService.getPlayersCount() == configRoomService.oneDeskhavePlayerCount) {
										haveWaitPlayerDeskServices.remove(roomDeskService);
										//桌子还在等人状态直接进入开局态度
//										if (roomDeskService.configDesk.getGameState() == DictionaryTabel.Game_WaitPlayer) {
//											roomDeskService.configDesk.setGameState(DictionaryTabel.Game_BeginJu);
//											roomDeskService.setPlayersStatus(DictionaryTabel.player_waitNextJu, DictionaryTabel.player_xiazhu);
//										}
									}
									
									if (dps.playerService.deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_People) {
										//加载进度条
										DataService.intoDesk(dps.playerService.deskPlayer.getPlayerId(), 
												dps.playerService.deskPlayer.getGameNum(), dps.playerService.deskPlayer.getRoomNum(), 
												dps.playerService.deskPlayer.getDeskNum(), dps.playerService.deskPlayer.getSeatNum());
									} else {
										AndroidService androidService = (AndroidService) dps;
										if (!androidManage.androidServices_Useing.contains(androidService))
											androidManage.androidServices_Useing.add(androidService);
									}
								} else {
									//加入桌子失败
									if (dps.playerService.deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_People) {
										dps.playerService.sendMessage(SocketEnum.infoI, TishiManager.Tishi_T_HavePlayer);
									} else {
										AndroidService adroidService = (AndroidService) dps;
										androidManage.androidServices_Useing.remove(adroidService);	
										
										if (!androidManage.androidServices_Available.contains(adroidService))
											androidManage.androidServices_Available.add(adroidService);
									}
								}
							} else {
								if (dps.playerService.deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_People) {
									dps.playerService.sendMessage(SocketEnum.infoI,TishiManager.Tishi_T_No_Seat);
								} else {
									AndroidService adroidService = (AndroidService) dps;
									androidManage.androidServices_Useing.remove(adroidService);
									
									if (!androidManage.androidServices_Available.contains(adroidService))
										androidManage.androidServices_Available.add(adroidService);
								}
							}
						} catch (Exception e) {
							logger.error(e.getMessage(), e);
							if (dps.playerService.deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_People) {
								dps.playerService.sendMessage(SocketEnum.infoI,TishiManager.Tishi_T_JoinDesk_Fail);
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		scheduExec.scheduleWithFixedDelay(task, 0, 1000, TimeUnit.MILLISECONDS);
	}

	private synchronized RoomDeskService getHaveWaitPlayerDeskService(DeskPlayerService dps){
		RoomDeskService roomDeskService = null;
		try {
			System.out.println("haveWaitPlayerDeskServices大小："+haveWaitPlayerDeskServices);
			if (haveWaitPlayerDeskServices.size() > 0 ) {
				if (dps.playerService.deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_People) {
					Iterator<RoomDeskService> ite = haveWaitPlayerDeskServices.iterator();
					while (ite.hasNext()) {
						RoomDeskService rds = ite.next();
						if (rds.getRealPlayersCount() > 0 && isCanJoin(rds, dps)) {
							roomDeskService = rds;
							break;
						}
					}
				} 
				
				if (roomDeskService == null)
					roomDeskService = haveWaitPlayerDeskServices.get(0);
				
				if (isCanJoin(roomDeskService, dps))
					return roomDeskService;
				
				roomDeskService = null;
			}
			
			if (roomDeskService == null) {
				//无等待桌子，随机一个初始位置加入
				int deskId = WDataConversion.randInt(0, configRoomService.oneRoomhaveDeskCount);
				for	(int i = deskId ; i < configRoomService.oneRoomhaveDeskCount ; i ++ ) {
					roomDeskService = roomDeskServices[i];
					if (isCanJoin(roomDeskService, dps))
						return roomDeskService;
				}
				
				for	(int i = deskId ; i >= 0 ; i -- ) {
					roomDeskService = roomDeskServices[i];
					if (isCanJoin(roomDeskService, dps))
						return roomDeskService;
				}
			}
			
		} catch (Exception e) {
			logger.info(e.getMessage(), e);
		}
		
		return null;
	}
	
	private boolean isCanJoin(RoomDeskService roomDeskService, DeskPlayerService dps){
		if (roomDeskService == null){
			return false;
		}
		if (!roomDeskService.configDesk.isDelayClose()) {
			if (dps.playerService.deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_People) {
				for (int i = 0; i < roomDeskService.deskPlayerServices.length; i++) {
					if (roomDeskService.deskPlayerServices[i] == null)
						return true;
				}
			} else {
				int playerCount = roomDeskService.getPlayersCount();
				int realCount = roomDeskService.getRealPlayersCount();
				System.out.println("playerCount"+playerCount);
				System.out.println("realCount"+realCount);
				if (realCount == 0 && playerCount == configRoomService.oneDeskhavePlayerCount - 2) {
					return false;
				} else if (playerCount < configRoomService.oneDeskhavePlayerCount) {
					for (int i = 0; i < roomDeskService.deskPlayerServices.length; i++) {
						if (roomDeskService.deskPlayerServices[i] != null && 
							roomDeskService.deskPlayerServices[i].playerService.deskPlayer.getPlayerId() == dps.playerService.deskPlayer.getPlayerId()) {
							return false;
						}
					}
					return true;
				}
			}
		}
		return false;
	}
//	public void begin(IoSession session, String content) {
//		try {
//			int deskNum = Integer.valueOf(session.getAttribute("deskNum") + "");
//			getRoomDeskServices()[deskNum].begin(session,content);
//		} catch (Exception e) {
//			// TODO: handle exception
//			throw e;
//		}
//	}
	
	public void getPlayerInfo(IoSession session) {
		try {
			sendPlayerListInfo(session);
		} catch (Exception e) {
			// TODO: handle exception
			throw e;
		}
	}
	
	public void sendPlayerListInfo(IoSession session) {
		int deskNum = Integer.valueOf(session.getAttribute("deskNum") + "");
		int i = 0;
		if (deskNum <= 19) {
			i = 0;
		} else {
			i = deskNum - 19;
		}
		JSONArray jsonArray = new JSONArray();
		int count = (i + 19) <= getRoomDeskServices().length ? i + 19 : getRoomDeskServices().length;
		// System.out.println("取-->" + i + "到" + count);
			RoomDeskService deskService = getRoomDeskServices()[deskNum];
			DeskPlayerService[] playerDeskService = deskService.deskPlayerServices;
			if (playerDeskService.length > 0) {
				for (DeskPlayerService dps : playerDeskService) {
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("playerName", dps.playerService.deskPlayer.getNickName());
					jsonObject.put("headUrl", dps.playerService.deskPlayer.getHeadUrl());
					jsonObject.put("playerId", dps.playerService.deskPlayer.getPlayerId());
					jsonObject.put("money", dps.playerService.getPropNum(2));
					jsonObject.put("vipLevel", dps.playerService.deskPlayer.getVipLevel());
					jsonObject.put("seatId", i);
					jsonArray.add(jsonObject);
				}
				
			}
		
		session.write(SocketEnum.playerAllListI + "@" + jsonArray.toString() + "@&");
	}
}
